<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class themeModel extends QueryModel
{

    protected $table = 'site_theme_table';

    /**
     * 获取主题列表
     * @param int $status
     * @param string $author
     * @param string $name
     * @param string $license
     * @return Response
     */
    public function getThemeList(
        int $status,
        string $author,
        string $name,
        string $license
    ): Response {
        $where = [];

        if ($status > -1) {
            $where['status'] = $status;
        }

        if ($license !== '') {
            $where['license'] = $license;
        }

        $query = $this->where($where);

        if ($author !== '') {
            $query -> whereLike('site_theme_author', "%${author}%");
        }

        if ($name !== '') {
            $query -> whereLike('site_theme_name', "%${name}%");
        }

        return $this->paginateQuery($query);
    }

    /**
     * 通过ID获取单个主题
     * @param int $site_theme_id
     * @return array|null
     */
    public function getThemeFind(int $site_theme_id): ?array
    {
        $them = $this->where([
            'site_theme_id' => $site_theme_id
        ]) -> findOrEmpty();
        return $them -> isEmpty() ? null : $them -> toArray();
    }

    /**
     * 通过域名获取单个主题
     * @param string $domain
     * @return array|null
     */
    public function getThemeByDomain(string $domain): ?array
    {
        $them = $this->where([
            'site_theme_domain' => $domain
        ]) -> findOrEmpty();
        return $them -> isEmpty() ? null : $them -> toArray();
    }

    /**
     * 设置主题绑定的域名
     * @param string $domain
     * @param int $site_theme_id
     * @return Response
     */
    public function setThemeDomain(string $domain, int $site_theme_id): Response
    {
        if (!$domain) return message() -> parameter_error('请填写需要绑定的域名');
        $theme = $this->getThemeByDomain($domain);
        if ($theme) return message() -> update_failed('当前域名已绑定主题');

        $save = $this->update([
            'site_theme_domain' => $domain
        ], ['site_theme_id' => $site_theme_id]);
        return message() -> success('更新成功', $save -> toArray());
    }
}